#ifdef _WIN32
#include "tword.h"

int
utf8_to_unicode(char* in, char *out)
{
	int len = strlen(in);
	int i, j, k;

	for (i = 0, j = 0, k = 0; i < len; j += 2) {
		if (((in[i] >> 3) & 0x1E) == 0x1E) {
			// 11110xxx
			// don't know how to convert it to 16bits unicode, tbd??
		} else if (((in[i] >> 4) & 0x0E) == 0x0E) {
			// 1110xxxx
			out[j] = ((in[i + 1] & 0x03) << 6) + (in[i + 2] & 0x3F);
			out[j + 1] = ((in[i] & 0x0F) << 4) + ((in[i + 1] >> 2) & 0x0F);
			i += 3;
		} else if (((in[i] >> 5) & 0x07) == 0x06) {
			// 110xxxxx
			out[j] = (in[i] >> 2) & 0x07;
			out[j + 1] = ((in[i] & 0x03) << 6) + (in[i + 1] & 0x3F);
			i += 2;				
		} else if (((in[i] >> 7) & 0x01) == 0) {
			//0xxxxxxx <ASCII>
			out[j] = in[i];
			out[j + 1] = 0X00;
			i += 1;
		}
		k += 1;
	}

	return k;
}

int
convert_charset(char *in, char *out, int len)
{
	char unicode_buf[MAX_BUFLINE_SIZE];
	int unicode_size, multi_size;

	unicode_size = utf8_to_unicode(in, unicode_buf);
	multi_size = WideCharToMultiByte(CP_ACP, NULL, &unicode_buf, 
					 unicode_size ,out,
					 len, NULL, NULL);

	return multi_size;
}

char *
strndup(const char *str, int len)
{
	char in[MAX_BUFLINE_SIZE];
	char out[MAX_BUFLINE_SIZE];
	int size;
	char *p;
	
	memcpy(in, str, len);
	*(in + len) = '\0';
	size = convert_charset(in, out, MAX_BUFLINE_SIZE);
	p = (char*)DMALLOC(sizeof(char)*(size + 1));
	if (p != NULL) {
		memcpy(p, out, size);
		*(p + size) = '\0';
	}
	return p;
}
#endif

